package com.eureka.listener;

import com.netflix.appinfo.InstanceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.eureka.server.event.*;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务监听
 * @see org.springframework.cloud.netflix.eureka.server.event;
 * 基于spring 事件驱动模型实现
 * */
@Component
public class EurekaServerStateChangeListener {


    private static final Logger log = LoggerFactory.getLogger(EurekaServerStateChangeListener.class);

    private final ConcurrentHashMap<String,Map<String,InstanceInfo>> listenResult = new ConcurrentHashMap<String, Map<String, InstanceInfo>>();

    /**
     * 服务下线监听
     * */
    @EventListener
    public void listenCanceled(EurekaInstanceCanceledEvent canceledEvent){

        log.info("服务：{} 已下线，服务Id：{}",canceledEvent.getAppName(),canceledEvent.getServerId());
        log.info(canceledEvent.toString());
        //sendServerCanceledEmail
        log.warn("开始发送服务下线邮件");

    }

    /**
     * 已注册的服务监听
     * */
    @EventListener
    public void listenRegistered(EurekaInstanceRegisteredEvent registeredEvent){
        InstanceInfo instanceInfo = registeredEvent.getInstanceInfo();
        log.info("服务：{} 已注册，服务Id：{}",instanceInfo.getAppName(),instanceInfo.getInstanceId());
    }

    /**
     * 注册中心服务注册监听
     * */
    @EventListener
    public void listenRegistryAvailable(EurekaRegistryAvailableEvent registryAvailableEvent){
        log.info(""+registryAvailableEvent.getSource());
    }

    /**
     * 服务续约监听
     * */
    @EventListener
    public void listenRenewed(EurekaInstanceRenewedEvent renewedEvent){
        log.info("服务：{} 已成功续约，服务Id：{}",renewedEvent.getAppName(),renewedEvent.getServerId());
    }

    /**
     * Eureka服务启动监听
     * */
    @EventListener
    public void listenStarted(EurekaServerStartedEvent startedEvent){
        log.info("Eureka Server 服务在端口：{}，成功启动！","8002");
    }


    public Map<String,Map<String,InstanceInfo>> eventListenResult(EurekaInstanceRegisteredEvent registeredEvent){
        Map<String,InstanceInfo> instanceInfoMap = new HashMap<>();
        instanceInfoMap.put("Registered",registeredEvent.getInstanceInfo());
        listenResult.put("Canceled",instanceInfoMap);
        return listenResult;
    }

}
